package com.github.icloudpay.pay.core.service.pay.wechat.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.icloudpay.pay.core.service.pay.LocalSignatureService;
import com.github.wxiaoqi.security.common.util.BeanUtils;

/** 
* @author: bolei
* @date：2017年4月30日 下午2:03:47 
* @description：微信服务签名
*/
@Service("wechatSignatureService")
public class WechatSignatureService {
	
	@Autowired
	private LocalSignatureService localSignatureService;
	
	static Logger LOG = LoggerFactory.getLogger(WechatSignatureService.class);

	public String sign(Object obj, Map<String, Object> configMap) throws Exception{
		return toSign(BeanUtils.objectToMap(obj), configMap);
	}

	public String toSign(Map<String, Object> sPara, Map<String, Object> configMap) {
		String result = createLinkString(sPara);
		LOG.debug("=============待签名微信数据Map: {}", result);
		return localSignatureService.sign(result, configMap);
	}
	
	/**
	 * 验签服务
	 */
	public boolean vailSign(Map<String, Object> map, String sign, Map<String, Object> configMap) {
		if (toSign(map, configMap).equals(sign)) {
			return true;
		} else {
			return false;
		}
	}
	
	private String createLinkString(Map<String, Object> params) {

		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		String prestr = "";

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			if (!"sign".equals(key)) {
				Object obj = params.get(key);
				if (obj == null || "".equals(obj)) {
					continue;
				}
				String value = String.valueOf(obj);
				prestr = prestr + key + "=" + value + "&";
			}
		}

		return prestr.substring(0, prestr.length() - 1);

	}

}
